﻿namespace WPFDBBrowser.DBTreeView
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Controls;
    using System.Windows;
    using WPFDBBrowser.Interfaces.DBTreeView;

    public class TreeTemplateSelector : DataTemplateSelector
    {
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            if (item != null)
            {
                FrameworkElement element = container as FrameworkElement;
                if (element != null)
                {
                    string templateName = null;
                    if (item is IGenericContainer ||
                        item is IColumnContainer)
                        templateName = "hierarchicalTreeViewItemTemplate";
                    else if (item is IColumn)
                        templateName = "columnTreeViewItemTemplate";
                    else
                        templateName = this.TryLoadGenericType(item.GetType());
                    if (string.IsNullOrEmpty(templateName) && item is IDBItem)
                        templateName = "treeViewItemTemplate";
                    if (!string.IsNullOrEmpty(templateName))
                        return element.TryFindResource(templateName) as HierarchicalDataTemplate;
                    else
                        return null;
                }
            }
            return base.SelectTemplate(item, container);
        }

        private string TryLoadGenericType(Type type)
        {
            while (type.BaseType != null)
            {
                if (type.BaseType.FullName.Contains("WPFDBBrowser.Interfaces.DBTreeView.DBHierarchicalItem"))
                    return "hierarchicalTreeViewItemTemplate";
                type = type.BaseType;
            }
            return null;
        }
    }
}
